package com.qf.openapi.web.master.service.impl;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageHelper;
import com.qf.openapi.web.master.dao.UserDao;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.exception.UserException;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserRegistVo;
import net.sf.jsqlparser.statement.select.Limit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    //    @Value("${uploadpath}")
    private String filepath = "E:\\JavaProject\\Idea\\File\\file\\";

    @Autowired
    UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    @Transactional(rollbackFor = Exception.class)

    @Override
    public User getUserByName(String username) {
        return userDao.getUserByName(username);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User login(String username, String password) {
        //1.根据用户名查询用户信息
        User user = userDao.getUserByName(username);
        if (user == null) {
            //没有匹配的用户返回null
            return null;
        } else { //2.比对密码是否正确
            String password1 = user.getPassword();
            //转换password参数为md5字符串
            String md5password = DigestUtil.md5Hex(password);
            if (password1.equals(md5password)) {
                return user;
            }
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addUser(UserRegistVo user, MultipartFile file) throws IOException {
        User user1 = new User();
        String newFile = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        String finaFilepath = filepath + newFile;
        File file1 = new File(finaFilepath);
        file.transferTo(file1);
        //密码加密
        String md5Hex = DigestUtil.md5Hex(user.getPassword());
        user1.setName(user.getName());
        user1.setPassword(md5Hex);
        user1.setSex(user.getSex());
        user1.setBirthday(user.getBirthday());
        user1.setRegistTime(new Date());
        user1.setPhotopath(file1.toString());
        int count = userDao.addUser(user1);
        if (count != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public TableVo selectAll(Integer page, Integer limit, String name, String sex, String birthday) {
        PageHelper.startPage(page, limit);
        List<User> users = userDao.selectAll(name, sex, birthday);
        int countAll = userDao.countAll();
        return TableVo.ok(countAll, users);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertUser(UserRegistVo userRegistVo) throws UserException {
        User userByName = userDao.getUserByName(userRegistVo.getName());
        if (userByName == null) {
            String md5Hex = DigestUtil.md5Hex(userRegistVo.getPassword());
            User user = new User(null, userRegistVo.getName(), md5Hex, userRegistVo.getSex(), userRegistVo.getBirthday(), userRegistVo.getRegistTime(), null);
            int index = userDao.insertUser(user);
            if (index != 0) {
                return true;
            }
        }
        throw new UserException(-1001, "用户名重复");
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteUser(Integer[] ids) {
        int index = 0;
        for (int i = 0; i < ids.length; i++) {
            index = userDao.deleteUser(ids[i]);
        }
        if (index != 0) {
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(UserRegistVo userRegistVo) throws UserException {

        int id = userRegistVo.getId();
        String voPassword = userRegistVo.getPassword(); //123456
        User user = new User(null, userRegistVo.getName(), voPassword, userRegistVo.getSex(), userRegistVo.getBirthday(), userRegistVo.getRegistTime(), null);
        String password = userDao.getUserById(id).getPassword(); //dffyufjfhjfhtjtfy
        if (!password.equals(voPassword)) {
            String md5Hex = DigestUtil.md5Hex(password); //123456-->fyugkjgjkkgjgk
            if (md5Hex.equals(voPassword)) {
                throw new UserException(-1, "密码重复");
            } else {
                user.setPassword(md5Hex);
            }
        }
        userDao.updateUser(user);
        return true;
    }

    @Override
    public String export() {
        List<User> allUser = userDao.getAllUser();
        String filename = UUID.randomUUID() + ".csv";
        String finalFilepath = filepath + filename;
        CsvWriter writer = CsvUtil.getWriter(finalFilepath, StandardCharsets.UTF_8);
        writer.writeBeans(allUser);//把集合里的数据写到finalFilepath里
        return filename;
    }

    @Override
    public void getListUser(MultipartFile file) throws IOException {
        String filename = UUID.randomUUID() + ".csv";
        String finalFilepath = filepath + filename;
        file.transferTo(new File(finalFilepath));//
        CsvReader reader = CsvUtil.getReader();
        List<User> userList = reader.read(ResourceUtil.getUtf8Reader(finalFilepath), User.class);
        for (User user : userList) {
            System.out.println(user);
        }
        userDao.insertListUser(userList);
    }
}


